package sis.ra.sap.nameentity;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;

import sis.ra.utility.Utils;

import com.inxight.IMS;
import com.inxight.IMSException;
import com.inxight.IMSResultSizeException;

/**
 * Extract Entities using Inxight ThingFinder
 * Copyright 2004 SAP
 * All right reserved.
 * @author I820753
 * Created on 8 Apr 2009
 */
public class ExtractEntity {
	public static String IMS_HOST="localhost";
	/**
	 * extract the entity list from the xml file which is the result returned from Inxight ThingFinder
	 * @return ArrayList<InxEntity>
	 * @param xmlContent
	 * @return
	 */
	public static ArrayList<InxEntity> parseIMSXMLContentList(String xmlContent)
	{
		ArrayList<InxEntity> ens = new ArrayList<InxEntity>();
		ArrayList<String> names=new ArrayList<String> ();
		Document document = null;
		try {
//			document = new SAXBuilder().build(systemId)
//			System.out.println(xmlContent);
			document = new SAXBuilder().build(new StringReader(xmlContent));
		
		Element root = document.getRootElement();
		Namespace inx = root.getNamespace("inxenv");
		Namespace inx2 = Namespace.getNamespace("http://www.inxight.com/ims/response/4.6");

		Element docprocnode = root.getChild("payload",inx).getChild("document-processing",inx2);
		Element entitylist= docprocnode.getChild("extract-entities",inx2).getChild("entities",inx2);
		List children = entitylist.getChildren("entity",inx2);
		for (Object entity : children) {
			Element el = (Element)entity;
			String canonical=el.getAttributeValue("canonical");
			String canonicaltype=el.getAttributeValue("canonical-type");
			String surface=el.getAttributeValue("surface");
			String entitytype=el.getAttributeValue("entity-type");
			String offset=el.getAttributeValue("offset");
			String confidence=el.getAttributeValue("confidence");
			String relevance=el.getAttributeValue("relevance");
//		InxEntity en=new InxEntity("","", "",surface,entitytype,"");
//		public InxEntity(String canoical, String canoicalType, String confidence,
//		String entityType, String id, String offset, String position,
//		String relevance, String surface) {

			InxEntity en=new InxEntity(canonical, canonicaltype, confidence, entitytype, "", offset, "", relevance, surface);	
			ens.add(en);
		}
		
		} catch (Exception e) {
			System.out.println(xmlContent);
			e.printStackTrace();

		}
		return ens;
	}
	
	/**
	 * extract the entities from the content using Inxight ThingFinder, and return XML file
	 * @return String
	 * @param content
	 * @return
	 */
		public static String getNE(String content) {

			String nameentity="";
			byte[] response=null;
//			if (queryString.length()<1) {
//				System.out.println("queryString, You must enter a query.");
//				return "";			
//			}
	//		System.out.println(content);
			content = content.replaceAll("[^A-Za-z,.<>\"\'&()-]", " ");
	//		System.out.println("after");
	//		System.out.println(content);
		//	content=content.replace("-", " ").replace("(", " ").replace(")", " ");

			/*	< --> &lt;
			> --> &gt;
			& --> &amp;
			" --> &quot;
			' --> &apos;
			from Inxight ThingFinder, Customization Guide, chap1 p 9
			*/
			content=content.replace("&", "&amp;");
			content=content.replace("<", "&lt;");
			content=content.replace(">", "&gt;");
			content=content.replace("\"", "&quot;");
			content=content.replace("\'", "&apos;");
			
			String host = IMS_HOST; // assign the IMS server's host
			Integer port = new Integer(55555); // assign the IMS server's port number
			int timeout = 300; // default to 300 seconds (5 mins)

			String config_file = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n"
			+ "<inxight:inxight-xml xmlns:inxight=\"http://www.inxight.com/envelope\">\n"
			+ "<inxight:header>   \n "
			+ "<inxight:description>Extract Entities</inxight:description>    \n"
			+ "<inxight:sender>Sender</inxight:sender>  \n"
			+ "  <inxight:receiver>Receiver</inxight:receiver> \n"
			+ " </inxight:header> \n "
			+ "<inxight:payload>  \n "
			+ " <document-processing xmlns=\"http://www.inxight.com/ims/request/4.6\">\n"
			+ "      <document>        \n"
			+ "<content> "+content+" </content>\n"
			+ "      </document>   \n"
			+ "   <extract-entities language=\"english\" conjecture=\"true\" aliasing=\"true\" relevance-rank=\"true\""
			+ " doc-image=\"true\" use-advanced-parsing=\"true\">\n"
			+ "</extract-entities>\n" + "</document-processing>\n"
			+ "</inxight:payload>\n" + "</inxight:inxight-xml>\n";

	//		System.out.println(config_file);
			byte[] buffer = config_file.getBytes();
			//        out.println("file  "+filename +"</br>");
			//        out.println("config file content: "+ config_file +"</br>");

			try {
			// connect to the IMS server
			IMS ims = new IMS(host, port.intValue());
		
			// send one request to the server
			long maxBufSize = 10000000; // Maximum number of bytes client will accept from server.
		
			
			response = ims.SubmitRPCTaskBuffer(IMS.TASK_IMS, buffer,
					IMS.PLACE_AT_TAIL, maxBufSize, timeout);
	//			System.out.println(response);
			ims.Disconnect();
			//TODO: remove temp file
		
			
		} catch (IMSException ce) {
			System.out.println("} catch (IMSException ce ){");
	//		System.out.println(ce.toString());
		
		} catch (java.net.UnknownHostException ce) {
			System.out.println("unknown host: "+host);
	//		System.out.println(ce.toString());
		} catch (java.io.IOException ce) {
			ce.printStackTrace();	
		} catch (IMSResultSizeException ce) {
			ce.printStackTrace();
			}
			nameentity=new String (response);
		return nameentity;
	}

	public static void main(String[] args) {
	//	String url="http://cis3.pal.sap.corp:8080/TopicTrackerBI/www/TranslationSmall.txt";
	//	String content=Utils.fetchContentfrURL(url);
		String content = "Google, Mountain view";
	//	content = content.replaceAll("[^A-Za-z<>\"\'&()-]", " ");
		System.out.println(content);
		String xml = getNE(content);
		System.out.println(xml);
	}

}
